template.defaults.imports.CountdownTime = function (factEndDate) {
    var timestamp = (new Date()).valueOf();
    return factEndDate - timestamp;
};

    /* global orderStates */
    var loading = false; //状态标记
    var hasNextPage = false;
    var pageNo = 1;
    var orderState = orderStates;
    queryList(pageNo);

    //下拉刷新
    $("#aroundBox").pullToRefresh().on("pull-to-refresh", function () {
        $("#contentTo").html("");
        pageNo = 1;
        queryList(pageNo,function(){
            $("#aroundBox").pullToRefreshDone(); // 重置下拉刷新
        });
    });
  
    //上拉加载更多
    $('#aroundBox').infinite().on("infinite", function () {
        if (hasNextPage){
            pageNo++;
            queryList(pageNo,function(){
            },true);
        }        
    });

    function queryList(pageNo,callback,isMore){
        if (loading) return;
        loading = true;
        var params = {};
        params.start = (pageNo - 1) * 20;
        params.limit = 20;
         /* global getCookie */
         /* global orderState */
        params.token = getCookie('token');
        params.state = orderState;
        if (orderState == -1) {
            delete params.state;
        } 


        $.get('/antique/api/mallOrder/user/query_order_list', params, function (result) {
            if (result.code == 0) {
                if (!isMore){
                    /* global template */
                    document.getElementById('contentTo').innerHTML = template('content', result.data);                
                } else {
                    $("#contentTo").append(template('content', result.data));
                }
                hasNextPage = result.data.hasNextPage;
                if (!result.data.hasNextPage) {
                    $('#loadmore').hide();
                    $('#nomore').show();
                } else {
                    $('#loadmore').show();
                    $('#nomore').hide();
                }
                if (callback) callback();
                loading = false;
            }

            
        });
    }
$(".weui-tab .tabs .item").click(function () {
        $(".weui-tab .tabs .item").removeClass("current");
        $(this).addClass("current");
    
        orderState = $(this).data('state');
        $("#contentTo").html("");
        pageNo = 1;
        queryList(pageNo,function(){
            $("#aroundBox").pullToRefreshDone(); // 重置下拉刷新
        });
        
    });

function sureReceive (orderId) {
    $.confirm("您是否确认收货？", "", function() {
        $.post('/antique/api/mallOrder/user/order_receive_goods', { id:orderId,token:getCookie('token') }, function (result) {
            if (result.code == 0) { 
                visitUrl('/add_evaluate?id=' + orderId, true);
                // $.toast("操作成功！");
                // $("#contentTo").html("");
                // pageNo = 1;
                // queryList(pageNo,function(){},true);
            } else {
             $.toast(result.message, "cancel");
            }
         });
      }, function() {
        //取消操作
      });
    
}
function delayPay (id) {
    $.confirm("延迟付款可推迟7天付款,一个订单可延迟一次", "", function() {
        $.post('/antique/api/mallOrder/user/order_pay_delay', { id:id,token:getCookie('token') }, function (result) {
            if (result.code == 0) {
                $.toast("操作成功！");
                $("#contentTo").html("");
                pageNo = 1;
                queryList(pageNo,function(){},true);
            } else {
             $.toast(result.message, "cancel");
            }
         });
      }, function() {
        //取消操作
      });
    
}


function payOrder (orderId,money) {
    // $("#payMoney").html(money);
    // $("#payId").val(orderId);
    //$("#pay_deposit").popup();
    adreeList(orderId,money);
}
function adreeList (orderId,money){
    var params = {};
    params.start = 0;
    params.limit = 1000;
    /* global getCookie orderId visitUrl*/
    params.token = getCookie('token');
    $.get('/antique/api/userAddress/query_list', params, function (result) {
        /* global template */
        var returnParams = result.data;
        returnParams.orderId = orderId;
        returnParams.money = money;
       
        $("#adressContent").html(template('adressContenTo', returnParams));

        $(".address .item").click(function () {
            $(".address .item").removeClass("current");
            $(this).addClass("current");
        
        });
        $("#select_adress").popup();

    });
    
}
function choseAdree (orderId,money) {
    var id = $(".address .current").data('aid');
    if (id == ''){
        $.toast("地址不能为空", "cancel");
        return;
    }
    if (orderId == ''){
        $.toast("参数错误", "cancel");
        return;
    }
    $.post('/antique/api/mallOrder/user/order_update_detail', { id:orderId,token:getCookie('token'),receiveAddressId:id }, function (result) {
        if (result.code == 0) {
            $.closePopup();
            $("#payMoney").html(money);
            $("#payId").val(orderId);
            $("#pay_deposit").popup();
        } else {
            $.toast(result.message, "cancel");
        }
    });
  }
function closePopup(){
    $.closePopup();
}
/* global servicePay */
$("#confirmBondPay").click(function(){
    var type = $("input[name='radioPay']:checked").val();
    var orderId = $("#payId").val();
    var payMoney = $("#payMoney").html();
    if (orderId == ''){
        $.toast("参数错误", "cancel");
        return;
    }
    if (type == 1) {
        passwordPay(orderId);
    } else if (type == 2) {
        /* global isMiniProgram wx */
        if ( isMiniProgram () ) {//小程序就跳转小程序支付
            var params = {
                type: 110,//支付类型
                id: orderId,//关联id
                payMoney: payMoney,//支付金额
                content:'购买商品',//订单说明
                jumpUrl:'/pages/order/index',//支付成功后跳转地址  为空返回当前页面 不可以带 ? 和 &
              };
            wx.miniProgram.navigateTo({
                url: "/pages/pay/index?params=" + JSON.stringify(params)
            });
        } else {
            $.post('/antique/api/onlinePay/wxpay/create_wxpay', {
                token:getCookie('token'),
                type:110,
                appSource:1,
                keyId:orderId,
                money:servicePay(payMoney),
                content:'购买商品' + payMoney
            }, function (result) {
                var appId = result.data.appid;
                var nonceStr = result.data.nonce_str;
                var prepay_id = result.data.prepay_id;
                var mch_id = result.data.mch_id;
                /* global goWeiPay */
                goWeiPay(appId,nonceStr,prepay_id,mch_id);
            });
        }
    }

});
function passwordPay (orderId) {
    /* global havePayPwd */
    havePayPwd (function(havePwd) {
        if (havePwd) {
            $.modal({
                title: "请输入支付密码",
                text: '<input class="weui-input weui-prompt-input" type="password" id="password"  placeholder="没有设置密码可不填" />',
                buttons: [ 
                  { text: "取消", className: "default" },
                  { text: "确定", onClick: function(){
                    submitAdd(orderId,$("#password").val());
                   } }
                  
                ]
            });
        } else {
            submitAdd(orderId,'');
        }
    })
    
    
    
}
/* global timeToTimestamp  hex_md5*/
function submitAdd(orderId,password){
    var params = {};
    params.id = orderId;
    params.token = getCookie('token');
    var time = timeToTimestamp(new Date());
    if (password == '') {
        params.payPass = hex_md5(time + '').toUpperCase(); 
    } else {
        var passwords = hex_md5(password).toUpperCase();
        params.payPass = hex_md5(passwords + time).toUpperCase();
    }
    params.time = time;
    $.ajax({
        type:'POST',
        url:"/antique/api/mallOrder/user/order_pay",
        data: params,
        dataType:"json",
        success:function(res){
            if (res.code == 0){
                $.toast("付款成功");
                $("#contentTo").html("");
                pageNo = 1;
                queryList(pageNo,function(){},true);
             } else {
                $.toast(res.message, "cancel");
            }
            
        }
    });
      

} 